package com.snap.awesomeserial.framework;

import android.os.Handler;
import android.os.Looper;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * //
 * Created by Eason on 2019-07-23 .
 */
public class MoleExecutor {

    private static MoleExecutor sInstance;

    private Handler handler;
    private ExecutorService executor;
    private List<Future> futures = new ArrayList<>();

    private MoleExecutor() {
        handler = new Handler(Looper.getMainLooper());
        executor = Executors.newCachedThreadPool();
    }

    public synchronized static MoleExecutor getInstance() {
        if (sInstance == null) {
            sInstance = new MoleExecutor();
        }

        return sInstance;
    }

    public void execute(Runnable runnable) {
        Future f = executor.submit(runnable);
        futures.add(f);
    }

    public <T> void execute(MoleTask<T> task) {
        Future f = executor.submit(new MoleRunnable<>(task));
        futures.add(f);
    }

    public void clear() {
        for (Future future : futures) {
            future.cancel(true);
        }
        futures.clear();
    }

    private class MoleRunnable<T> implements Callable<Void> {

        private MoleTask<T> task;

        MoleRunnable(MoleTask<T> task) {
            this.task = task;
        }

        @Override
        public Void call() throws Exception {
            T result = task.runInBackground();
            TimeUnit.MILLISECONDS.sleep(1);//给Thread.interrupt提供机会
            handler.post(() -> task.onCompleted(result));
            return null;
        }
    }
}
